package cn.edu.sdjzu.xg.eagle.controller;

import cn.edu.sdjzu.xg.eagle.entity.Teacher;
import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.service.TeacherService;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author tg.si@188.com
 * @todo
 * @since 2024/4/23 10:44
 */
@WebServlet({"/teacherModification/*", "/teacherModification"})
public class TeacherModificationCtrl extends HttpServlet {
    private TeacherService teacherService = null;

    @Override
    public void init() throws ServletException {
        teacherService = ServiceFactory.getService(TeacherService.class, "TeacherServiceImpl");
    }

    /**增加一个教师对象
    * {"no":"123",
     * "name":"Smith"
     * }
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //根据request对象，获得代表参数的JSON字串
        String teacher_json = JSONUtil.getJSON(request);
        //将JSON字串解析为Teacher对象
        Teacher teacherToAdd = JSON.parseObject(teacher_json, Teacher.class);

        //创建JSON对象message，以便往前端响应信息
        JSONObject msg = new JSONObject();
        //在数据库表中增加Teacher对象
        try {
            teacherService.add(teacherToAdd);
            msg.put("msg", "增加成功");
            msg.put("code","200");
            //log.error("成功！:");
        }catch (SQLException e){
            msg.put("msg", "数据库操作异常");
            msg.put("code","500");
            e.printStackTrace();
            // 记录SQLException的错误信息
            //log.error("数据库操作异常: {}", e.getMessage(), e);
        }catch(Exception e){
            msg.put("msg", "网络异常");
            msg.put("code","500");
            e.printStackTrace();
            // 记录其它的错误信息
            //log.error("网络异常: {}", e.getMessage(), e);
        }
        //响应message到前端
        response.getWriter().println(JSON.toJSONString(msg));

        //调用Service，添加对象
        //响应
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPut(req, resp);
    }
}
